package com.hlcl.huaji.server;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.elcl.network.AppContext;
import com.elcl.network.NetWorkUtils;
import com.elcl.storage.ApplicationCache;
import com.elcl.util.BaseDialogUtils;
import com.elcl.widget.comp.toast.ToastUtils;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by lichunlin on 16/8/8.
 */
public class OkHttpApp {

    public static final int IS_NET_FAILED = 0x404;//网络加载失败
    public static final int IS_NET_PWD_ERROR = 0x400;//输错密码
    public static final int IS_NET_CODE_ERROR = 0x405;//输错验证码

    private static FormEncodingBuilder builder = null;

    private static final OkHttpClient mOkHttpClient = new OkHttpClient();

    private static OkHttpApp okHttp;

    public static OkHttpApp getInstance() {
        if (null == okHttp) {
            okHttp = new OkHttpApp();
        }
        return okHttp;
    }

    static {
        mOkHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
    }

    public FormEncodingBuilder getFBuilder() {
        if (null == builder) {
            builder = new FormEncodingBuilder();
        }
        return builder;
    }

    //get请求
    public void get(String url, final Handler handler, final int reqId) {
        if (NetWorkUtils.isNetworkAvailable(ApplicationCache.context)) {
            getByServer(url, handler, reqId);
        } else {
            ToastUtils.showToast("没有网络连接");
        }
    }

    private void getByServer(String url, final Handler handler, final int reqId) {
        //创建okHttpClient对象
        Log.i("api", url);
        final Request request = new Request.Builder()
                .url(url)
                .addHeader("cache-control", "no-cache")
                .addHeader("content-type", "application/json")
                .addHeader("accept", "application/json")
                .addHeader("X-ml-APIKey", AppContext.getAppKey())
//                .addHeader("X-ml-AppId", AppContext.getAppId())
                .addHeader("X-ml-appid", AppContext.getAppId())
                .addHeader("x-ml-session-token", AppContext.getToken())
                .build();
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                ToastUtils.showToast("网络加载失败");
                BaseDialogUtils.dismissProgressDialog();
                handler.sendEmptyMessage(IS_NET_FAILED);
            }

            @Override
            public void onResponse(final Response response) throws IOException {
                BaseDialogUtils.dismissProgressDialog();
                responseSuccess(response, handler, reqId);
            }
        });
    }


    /*********************
     * post请求
     ********************/
    //post请求
    public void post(String url, String jsonContent, final Handler handler, final int reqId, String... isShow) {
        if (NetWorkUtils.isNetworkAvailable(ApplicationCache.context)) {
            Log.i("api", url);
            if (null != isShow && isShow.length > 0) {
                BaseDialogUtils.showProgressDialog("", isShow[0]);
            }
            postServer(url, jsonContent, handler, reqId);
        } else {
            ToastUtils.showToast("没有网络连接");
        }
    }

    private void postServer(String url, String jsonContent, final Handler handler, final int reqId) {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, jsonContent);
        Request request = null;
        if (reqId < 20) {//post请求
            request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("cache-control", "no-cache")
                    .addHeader("content-type", "application/json")
                    .addHeader("X-ml-APIKey", AppContext.getAppKey())
                    .addHeader("X-ml-appid", AppContext.getAppId())
                    .addHeader("x-ml-session-token", AppContext.getToken())
                    .build();
        } else {//put请求
            request = new Request.Builder()
                    .url(url)
                    .put(body)
                    .addHeader("cache-control", "no-cache")
                    .addHeader("Content-Type", "application/json")
//                    .addHeader("X-ml-APIKey", AppContext.getAppKey())
                    .addHeader("X-ML-AppId", AppContext.getAppId())
                    .addHeader("X-ML-Session-Token", AppContext.getToken())
                    .addHeader("X-ML-MasterKey", "TEoybVZmOE9Kc1hMRXJ5VU03bGpFUQ")
                    .build();
            String appId = AppContext.getAppId();
            String token = AppContext.getToken();
            Log.i("111", appId + token);
        }

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                BaseDialogUtils.dismissProgressDialog();
                ToastUtils.showToast("网络加载失败");
                handler.sendEmptyMessage(IS_NET_FAILED);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                BaseDialogUtils.dismissProgressDialog();
                responseSuccess(response, handler, reqId);
            }
        });
    }


    //{"errorMessage":"密码不匹配","errorCode":40010}
    private void responseSuccess(Response response, final Handler handler, final int reqId) {
        if (response.isSuccessful()) {
            try {
                String htmlStr = response.body().string();
                Log.i("api", htmlStr);

//                if (reqId == NetCode.ID_LOGIN_SCREAT) {//获取screat
//                    String x_las_screat = response.header("X-LAS-SECRET");
//
//                    Message msg = handler.obtainMessage();
//                    msg.obj = x_las_screat;
//                    msg.what = reqId;
//                    handler.sendMessage(msg);
//                } else {
//                    Message msg = handler.obtainMessage();
//                    msg.obj = htmlStr;
//                    msg.what = reqId;
//                    handler.sendMessage(msg);
//                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            int code = response.code();
            if (code == 400) {
                String htmlStr1 = null;
                try {
                    htmlStr1 = response.body().string();
                    JSONObject jsonObject = new JSONObject(htmlStr1);
                    int errorCode = jsonObject.getInt("errorCode");
                    String errorMessage = jsonObject.getString("errorMessage");

                    if (errorCode == 301) {//输入验证码
                        Message msg = handler.obtainMessage();
                        msg.obj = "";
                        msg.what = IS_NET_CODE_ERROR;
                        handler.sendMessage(msg);
                        return;
                    }else if(errorCode == 40010){
                        Message msg = handler.obtainMessage();
                        msg.obj = "";
                        msg.what = IS_NET_PWD_ERROR;
                        handler.sendMessage(msg);
                    }
                    ToastUtils.showToast(errorMessage);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }


//    public static final String TXT_HTML = "application/json";
//    public void postJson(String url, RequestBody requestBody, final Handler handler, final int reqId, String... isShow) {
//        if (NetWorkUtils.isNetworkAvailable(ApplicationCache.context)) {
//            if (null != isShow && isShow.length > 0) {
//                BaseDialogUtils.showProgressDialog("", isShow[0]);
//            }
//            postJsonServer(url, requestBody, handler, reqId);
//        } else {
//            SuccessToastUtils.showToast("没有网络连接");
//        }
//    }
//
//    private void postJsonServer(String url, RequestBody requestBody, final Handler handler, final int reqId) {
//        Request request = new Request.Builder()
//                .url(url)
//                .post(requestBody)
//                .build();
//        mOkHttpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Request request, IOException e) {
//                BaseDialogUtils.dismissProgressDialog();
//                SuccessToastUtils.showToast("网络加载失败");
//                handler.sendEmptyMessage(IS_NET_FAILED);
//            }
//
//            @Override
//            public void onResponse(Response response) throws IOException {
//                BaseDialogUtils.dismissProgressDialog();
//                responseSuccess(response, handler, reqId);
//            }
//        });
//    }


}
